﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.DataModel;
using YArchitech.HVAC;
using YArchitech.LIB;
using YArchitech.MEP;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class LaySprinklersByRectangle : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Dictionary<int, IList<RoutingPreferenceRule>> dictionary = null;
			int num = -1;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException();
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
				{
					(ViewType)1,
					(ViewType)2
				}))
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					IntPtr mainWindowHandle = Process.GetCurrentProcess().MainWindowHandle;
					this._hWndRevit = new YJKWindowHandle(mainWindowHandle);
					YJKRevitTools.GetFloorHeigh(document, activeUIDocument.ActiveView);
					HYEquipmentCommon hyequipmentCommon = new HYEquipmentCommon();
					SpaceFamilyDataReader spaceFamilyDataReader = new SpaceFamilyDataReader();
					LaySprinklerHelper laySprinklerHelper = new LaySprinklerHelper(document);
					FormLaySprinklerByRectangle formLaySprinklerByRectangle = new FormLaySprinklerByRectangle(document);
					SprinklerModelProcess sprinklerModelProcess = new SprinklerModelProcess(commandData, this._hWndRevit);
					if (formLaySprinklerByRectangle.ShowDialog() == DialogResult.Cancel)
					{
						result = Autodesk.Revit.UI.Result.Cancelled;
					}
					else
					{
						RectLayParamers rectParas = formLaySprinklerByRectangle.rectParas;
						FamilySymbol familySymbol = null;
						int num2 = 1;
						SprinklersParam sprinklersPara = formLaySprinklerByRectangle.sprinklersPara;
						LayAreaParameter layAreaParameter = formLaySprinklerByRectangle.layAreaParameter;
						if (formLaySprinklerByRectangle.CurrentBtn == 1)
						{
							familySymbol = formLaySprinklerByRectangle.Fsymbol;
						}
						else
						{
							familySymbol = spaceFamilyDataReader.GetFamilySymbolById(sprinklersPara.Id, "Sprinkler", sprinklersPara.SymbolName, document, BuiltInCategory.OST_Sprinklers);
							num2 = formLaySprinklerByRectangle.familyCategory;
						}
						int layTerminalType = formLaySprinklerByRectangle.layTerminalType;
						int familyConnStyle = formLaySprinklerByRectangle.familyConnStyle;
						if (num2 == 3)
						{
						}
						if (familySymbol == null)
						{
							result = Autodesk.Revit.UI.Result.Cancelled;
						}
						else
						{
							for (;;)
							{
								hyequipmentCommon.GetAllFamilyInstance(document, BuiltInCategory.OST_Sprinklers);
								hyequipmentCommon.GetAllFamilyInstance(document, BuiltInCategory.OST_PipeFitting);
								XYZ xyz = null;
								XYZ xyz2 = null;
								XYZ xyz3 = null;
								RecSprinklerHelper recSprinklerHelper = new RecSprinklerHelper(document);
								if (familySymbol != null)
								{
									ConnectHelper connectHelper = new ConnectHelper();
									new SprinklerShelter().GetPriorFitting(document);
									if (layTerminalType == 5)
									{
										if (layAreaParameter != null)
										{
											List<XYZ> list = new List<XYZ>();
											using (SprinklerRhombicJig sprinklerRhombicJig = new SprinklerRhombicJig(activeUIDocument))
											{
												xyz = sprinklerRhombicJig.startPoint(selection, layAreaParameter, sprinklersPara);
												if (xyz == null)
												{
													result = Autodesk.Revit.UI.Result.Succeeded;
													break;
												}
												xyz2 = sprinklerRhombicJig.endPoint(selection);
												list = sprinklerRhombicJig.xyzList;
												xyz3 = XYZ.Zero;
												if (list == null)
												{
													result = Autodesk.Revit.UI.Result.Succeeded;
													break;
												}
											}
											if (formLaySprinklerByRectangle.isAvoidColumns)
											{
												list = laySprinklerHelper.GetAvoidedXYZ(list);
											}
											sprinklerModelProcess.Go(familySymbol, formLaySprinklerByRectangle, list, xyz, xyz2, xyz3, true);
										}
										else
										{
											MessageBox.Show("布置失败，区域布置参数为空", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
										}
									}
									else if (layTerminalType == 3)
									{
										if (layAreaParameter != null)
										{
											List<XYZ> list2 = new List<XYZ>();
											if (rectParas != null)
											{
												using (SprinklerJig sprinklerJig = new SprinklerJig(activeUIDocument))
												{
													if (!sprinklerJig.startPoint(selection, rectParas) || !sprinklerJig.endPoint(selection))
													{
														result = Autodesk.Revit.UI.Result.Succeeded;
														break;
													}
													list2 = sprinklerJig.xyzList;
													if (list2 == null)
													{
														result = Autodesk.Revit.UI.Result.Succeeded;
														break;
													}
													xyz = sprinklerJig.rectParas.PointBase;
													xyz2 = sprinklerJig.PointEnd;
													xyz3 = sprinklerJig.rectParas.PointDiagonal;
													goto IL_4F3;
												}
												goto IL_2CB;
											}
											goto IL_2CB;
											IL_4F3:
											sprinklerModelProcess.Go(familySymbol, formLaySprinklerByRectangle, list2, xyz, xyz2, xyz3, true);
											continue;
											IL_2CB:
											if (!formLaySprinklerByRectangle.isThreePointLay)
											{
												xyz = selection.PickPoint("选择起始点坐标，此点为矩形的一个对角点");
												xyz2 = selection.PickPoint("选择终止点坐标，此点为矩形的另一个对角点");
												while (xyz.IsAlmostEqualTo(xyz2))
												{
													xyz2 = selection.PickPoint("选择终止点坐标，此点为矩形的另一个对角点");
												}
												if (layAreaParameter.LimitFlag == 1)
												{
                                                    list2 = connectHelper.CalculateLayFamilyInstanceXYZ(xyz, xyz2, layAreaParameter.RowCount, layAreaParameter.ColCount, layAreaParameter.Ratio, UnitConvert.CovertToAPI(sprinklersPara.OffSet * 1000.0, (DisplayUnitType)2), sprinklersPara.BeiShu);
												}
												else if (layAreaParameter.LimitFlag == 2)
												{
                                                    list2 = connectHelper.CalculateLaySprinklersXYZ(xyz, xyz2, layAreaParameter.RowDistance, layAreaParameter.ColDistance, layAreaParameter.RowDistanceSide, layAreaParameter.ColDistanceSide, layAreaParameter.LessDistance, UnitConvert.CovertToAPI(sprinklersPara.OffSet * 1000.0, (DisplayUnitType)2), sprinklersPara.BeiShu);
												}
												xyz3 = xyz2;
												xyz2 = new XYZ(xyz.X, xyz2.Y, xyz2.Z);
												goto IL_4F3;
											}
											xyz = selection.PickPoint("选择起始点坐标，此点为矩形的第一个边界点");
											xyz2 = selection.PickPoint("选择第二点坐标，此点为矩形的第二个边界点");
											while (xyz.IsAlmostEqualTo(xyz2))
											{
												xyz2 = selection.PickPoint("选择第二点坐标，此点为矩形的第二个边界点");
											}
											xyz3 = selection.PickPoint("选择终止点坐标，此点为矩形的第三个边界点");
											while (xyz3.IsAlmostEqualTo(xyz) || xyz3.IsAlmostEqualTo(xyz2))
											{
												xyz3 = selection.PickPoint("选择终止点坐标，此点为矩形的第三个边界点");
											}
											if (layAreaParameter.LimitFlag == 1)
											{
												list2 = connectHelper.CalculateLayFamilyInstanceXYZ(xyz, xyz2, xyz3, layAreaParameter.RowCount, layAreaParameter.ColCount, layAreaParameter.Ratio, UnitConvert.CovertToAPI(sprinklersPara.OffSet * 1000.0, (Autodesk.Revit.DB.DisplayUnitType)2));
											}
											else if (layAreaParameter.LimitFlag == 2)
											{
                                                list2 = connectHelper.CalculateLaySprinklersXYZ(xyz, xyz2, xyz3, layAreaParameter.RowDistance, layAreaParameter.ColDistance, layAreaParameter.RowDistanceSide, layAreaParameter.ColDistanceSide, layAreaParameter.LessDistance, UnitConvert.CovertToAPI(sprinklersPara.OffSet * 1000.0, (DisplayUnitType)2), sprinklersPara.BeiShu, true);
											}
											xyz3 = recSprinklerHelper.GetThreePoint(xyz, xyz2, xyz3);
											goto IL_4F3;
										}
										else
										{
											MessageBox.Show("布置失败，区域布置参数为空", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
										}
									}
								}
							}
						}
					}
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null && (int)transaction.GetStatus() != 3)
				{
					transaction.RollBack();
				}
				if (dictionary != null && num >= 0)
				{
					PipeConfigurationManagement.SetRules(num, commandData.Application.ActiveUIDocument.Document, dictionary, true);
				}
			}
			return result;
		}

		private void EndTransation(Transaction tran, bool beSure)
		{
			if (tran != null)
			{
				TransactionStatus status = tran.GetStatus();
				if ((int)status == 1)
				{
					if (beSure)
					{
						tran.Commit();
						return;
					}
					tran.RollBack();
					return;
				}
				else if ((int)status == 5)
				{
					tran.RollBack();
				}
			}
		}

		public YJKWindowHandle _hWndRevit;
	}
}
